﻿using Md.Api.DDD;
using Md.Api.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Md.Api.Controllers.Filters;
/// <summary>
/// Token验证拦截器
/// </summary>
public class MdAuthAttribute : ActionFilterAttribute
{
    internal const string Authorization = nameof(Authorization);
    /// <summary>
    /// 响应实体
    /// </summary>
    private ResponseMessageModel? Result { get; set; }
    /// <summary>
    /// Action方法调用之前执行
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // 跳过token验证,特殊接口不需要token验证
        var skipAuthorization = context.ActionDescriptor.EndpointMetadata.SingleOrDefault(a => a.GetType().Name.IndexOf("AllowAnonymousAttribute") > -1);

        if (skipAuthorization != null) return;

        var headers = context.HttpContext.Request.Headers;

        if (headers.ContainsKey(Authorization))
        {
            string token = headers[Authorization];

            var tokenRes = JwtHelp.GetJwtDecode(token.Split(" ")[1]);

            // token验证失败,失效或异常
            if (tokenRes.IndexOf("token") > -1)
            {
                Result = new ResponseMessageModel();
                Result.Msg = tokenRes;
                Result.Code = "401";
                Result.IsSuccess = false;

                context.Result = new OkObjectResult(Result);
            }
        }
        else
        {
            Result = new ResponseMessageModel();
            Result.Msg = "Unauthorized";
            Result.Code = "401";
            Result.IsSuccess = false;

            context.Result = new OkObjectResult(Result);
        }

        base.OnActionExecuting(context);
    }
    /// <summary>
    /// Action方法调用之后执行，Result方法调用前执行
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuted(ActionExecutedContext context)
    {
        // Console.WriteLine("---MdAuth OnActionExecuted---");
        base.OnActionExecuted(context);
    }
    /// <summary>
    /// Result方法调用之前执行
    /// </summary>
    /// <param name="context"></param>
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        // Console.WriteLine("---MdAuth OnResultExecuting---");
        base.OnResultExecuting(context);
    }
    /// <summary>
    /// Result方法调用之后执行
    /// </summary>
    /// <param name="context"></param>
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        // Console.WriteLine("---MdAuth OnResultExecuted---");
        base.OnResultExecuted(context);
    }
}

